package com.heima.search.service.Impl;

import com.heima.common.exception.CustException;
import com.heima.feigns.BehaviorFeign;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dto.HistorySearchDTO;
import com.heima.model.search.dto.UserSearchDTO;

import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.pojos.ApAssociateWords;
import com.heima.search.pojos.ApUserSearch;
import com.heima.search.service.ApUserSearchService;
import com.mongodb.client.result.DeleteResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.xml.ws.Response;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ApUserSearchServiceImpl implements ApUserSearchService {
    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    BehaviorFeign behaviorFeign;

    /**
     * 保存用户搜索历史记录
     *
     * @param userSearchDto
     */
    @Override
    @Async("taskExecutor")
    public void insert(UserSearchDTO userSearchDto) {
        //1 参数检查  搜索词
        String searchWords = userSearchDto.getSearchWords();
        Integer entryId = userSearchDto.getEntryId();
        //2 查询行为实体
        ResponseResult<ApBehaviorEntry> behaviorResponse = behaviorFeign.findByUserIdOrEquipmentId(entryId, userSearchDto.getEquipmentId());
        if (!behaviorResponse.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        ApBehaviorEntry apBehaviorEntry = behaviorResponse.getData();
        if (apBehaviorEntry == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        log.info("ApUserSearchServiceImpl insert entryId:{}, searchWords:{}", entryId, searchWords);
        //3 查询当前用户搜索的关键词是否存在
        ApUserSearch apUserSearch = mongoTemplate.findOne(Query.query(Criteria.where("entryId").is(entryId).and("keyword").is(searchWords)), ApUserSearch.class);
        //3.1 存在则更新最新时间，更新状态
        if (apUserSearch != null) {
            apUserSearch.setCreatedTime(new Date());
            mongoTemplate.save(apUserSearch);
            return;
        }
        //3.2 不存在则新增
        apUserSearch = new ApUserSearch();
        apUserSearch.setCreatedTime(new Date());
        apUserSearch.setEntryId(apBehaviorEntry.getId());
        apUserSearch.setKeyword(searchWords);
        mongoTemplate.save(apUserSearch);
        ApAssociateWords apAssociateWords = new ApAssociateWords();
        apAssociateWords.setId("1465278076978147330");
        apAssociateWords.setAssociateWords("文章发布");
        apAssociateWords.setCreatedTime(new Date());
        mongoTemplate.save(apAssociateWords);

    }

    /**
     * 查询用户搜索历史记录  显示10条
     *
     * @param userSearchDto
     * @return
     */


    @Override
    public ResponseResult findUserSearch(UserSearchDTO userSearchDto) {
        //1.检查参数  size=10  MinBehotTime=new Date()
        if (userSearchDto.getMinBehotTime() == null) {
            userSearchDto.setMinBehotTime(new Date());
        }
        int size=10;

        //2。查询实体
        ApUser user = AppThreadLocalUtils.getUser();

        ResponseResult<ApBehaviorEntry> behaviorResponse = behaviorFeign.findByUserIdOrEquipmentId(user == null ? null : user.getId(), userSearchDto.getEquipmentId());
        if (!behaviorResponse.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        ApBehaviorEntry apBehaviorEntry = behaviorResponse.getData();
        if (apBehaviorEntry == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3。查询mongo  行为实体id  创建时间<最小时间  按创建时间降序排序 limit size
        List<ApUserSearch> list = mongoTemplate.find(Query.query(Criteria.where("entryId").is(apBehaviorEntry.getId())
                .and("createdTime")
                .lt(userSearchDto.getMinBehotTime()))
                .with(Sort.by(Sort.Direction.DESC, "createdTime")), ApUserSearch.class);
        //4.返回数据

        return ResponseResult.okResult(list);
    }

    @Override
    public ResponseResult delUserSearch(HistorySearchDTO historySearchDto) {
      //参数校验
        if (historySearchDto.getId()==null){
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE);///500缺少参数
        }
        //拿行为实体
        ApUser user = AppThreadLocalUtils.getUser();
        ResponseResult<ApBehaviorEntry> behaviorEntryResponseResult = behaviorFeign.findByUserIdOrEquipmentId(user == null ? null : user.getId(), historySearchDto.getEquipmentId());

        if (behaviorEntryResponseResult==null){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程调用出错");//504
        }
        ApBehaviorEntry behaviorEntry = behaviorEntryResponseResult.getData();

        if (behaviorEntry==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);//1002数据不存在
        }
        //mongo删除根据id和行为实体id
        DeleteResult result = mongoTemplate.remove(Query.query(Criteria.where("_id").is(historySearchDto.getId()).and("entryId").is(behaviorEntry.getId())), ApUserSearch.class);

        return ResponseResult.okResult(result);
    }
}